from fastapi import APIRouter, Depends, status
from sqlalchemy.orm import Session
from typing import List, Optional

from config.Database import get_db
from schemas.NewInfoPush import NewInfoPushCreate, NewInfoPushUpdate, NewInfoPushResponse
from schemas.Result import Result
from services.NewInfoPushService import NewInfoPushService

router = APIRouter(
    prefix="/push",
    tags=["push"],
    responses={404: {"description": "Not found"}},
)

# 创建服务实例
new_info_push_service = NewInfoPushService()

# 创建新信息推送
@router.post("")
def create_new_info_push(new_info_push: NewInfoPushCreate, db: Session = Depends(get_db)) :
    # 检查count
    if new_info_push.count < 0:
        return Result.fail(msg="推送次数不能小于0")
    # 检查邮箱是否已存在
    first = new_info_push_service.get_by_email_first(db, new_info_push.email)
    if first:
        new_info_push_service.update(db,first.id,NewInfoPushUpdate(count=new_info_push.count))
        return Result.success(msg="订阅推送成功")
    else:
        # 创建新推送
        db_new_info_push = new_info_push_service.create(db, new_info_push)
        return Result.success(msg="订阅推送成功")

# 获取所有推送信息
@router.get("/all")
def get_all_new_info_pushes(skip: int = 0, limit: int = 10000, db: Session = Depends(get_db)):
    new_info_pushes = new_info_push_service.get_all(db, skip=skip, limit=limit)
    return Result.success(
        data=new_info_pushes,
        msg="获取推送列表成功"
    )

# 根据ID获取推送信息
@router.get("/{new_info_push_id}")
def get_new_info_push(new_info_push_id: int, db: Session = Depends(get_db)):
    new_info_push = new_info_push_service.get_by_id(db, new_info_push_id)
    if new_info_push is None:
        return Result.fail(msg="推送信息不存在", code=404)

    return Result.success(
        data=new_info_push,
        msg="获取推送信息成功"
    )

# 更新推送信息
@router.put("/{new_info_push_id}")
def update_new_info_push(new_info_push_id: int, new_info_push: NewInfoPushUpdate, db: Session = Depends(get_db)):
    updated_new_info_push = new_info_push_service.update(db, new_info_push_id, new_info_push)
    if updated_new_info_push is None:
        return Result.fail(msg="推送信息不存在", code=404)

    return Result.success(
        data=updated_new_info_push,
        msg="更新推送信息成功"
    )

# 删除推送信息（软删除）
@router.delete("/{new_info_push_id}")
def delete_new_info_push(new_info_push_id: int, db: Session = Depends(get_db)):
    success = new_info_push_service.delete(db, new_info_push_id)
    if not success:
        return Result.fail(msg="推送信息不存在", code=404)

    return Result.success(msg="取消订阅成功")

# 根据邮箱查询推送信息
@router.get("/email/{email}")
def get_new_info_pushes_by_email(email: str, db: Session = Depends(get_db)):
    new_info_pushes = new_info_push_service.get_by_email(db, email)
    return Result.success(
        data=new_info_pushes,
        msg="获取推送信息成功"
    )







